package com.bcu.cn.onlineexamsystem.studentmanage.service.impl;

import com.bcu.cn.onlineexamsystem.studentmanage.controller.ScoreAnalysisDTO;
import com.bcu.cn.onlineexamsystem.studentmanage.mapper.ScoreAnalysisMapper;
import com.bcu.cn.onlineexamsystem.studentmanage.service.ScoreAnalysisService;
import com.bcu.cn.onlineexamsystem.studentmanage.util.DataTypeConverter;
import com.bcu.cn.onlineexamsystem.studentmanage.util.DeepSeekUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 成绩分析服务实现类
 */
@Service
public class ScoreAnalysisServiceImpl implements ScoreAnalysisService {
    
    private static final Logger logger = LoggerFactory.getLogger(ScoreAnalysisServiceImpl.class);
    
    @Autowired
    private ScoreAnalysisMapper scoreAnalysisMapper;
    
    @Override
    public ScoreAnalysisDTO.ScoreStatistics getScoreStatistics(String studentId) {
        logger.info("=== 开始获取成绩统计数据 ===");
        logger.info("学生ID: {}", studentId);
        
        try {
            Map<String, Object> stats = scoreAnalysisMapper.getScoreStatistics(studentId);
            logger.info("查询统计数据: {}", stats);
            
            ScoreAnalysisDTO.ScoreStatistics statistics = new ScoreAnalysisDTO.ScoreStatistics();
            
            // 使用工具类安全转换数据类型
            statistics.setTotalExams(DataTypeConverter.toInteger(stats.get("total_exams")));
            statistics.setAverageScore(DataTypeConverter.toBigDecimal(stats.get("average_score")));
            statistics.setHighestScore(DataTypeConverter.toBigDecimal(stats.get("highest_score")));
            statistics.setLowestScore(DataTypeConverter.toBigDecimal(stats.get("lowest_score")));
            statistics.setPassCount(DataTypeConverter.toInteger(stats.get("pass_count")));
            statistics.setFailCount(DataTypeConverter.toInteger(stats.get("fail_count")));
            
            // 计算及格率
            Integer passCount = statistics.getPassCount();
            Integer totalExams = statistics.getTotalExams();
            if (totalExams != null && totalExams > 0) {
                BigDecimal passRate = new BigDecimal(passCount).divide(new BigDecimal(totalExams), 4, BigDecimal.ROUND_HALF_UP)
                        .multiply(new BigDecimal("100"));
                statistics.setPassRate(passRate);
            } else {
                statistics.setPassRate(BigDecimal.ZERO);
            }
            
            logger.info("统计数据获取完成: {}", statistics);
            return statistics;
            
        } catch (Exception e) {
            logger.error("获取成绩统计数据失败", e);
            throw new RuntimeException("获取成绩统计数据失败", e);
        }
    }
    
    @Override
    public List<ScoreAnalysisDTO.ExamRecord> getStudentExamRecords(String studentId) {
        return scoreAnalysisMapper.getStudentExamRecords(studentId);
    }
    
    @Override
    public List<ScoreAnalysisDTO.CourseScoreAnalysis> getCourseScoreAnalysis(String studentId) {
        logger.info("=== 开始获取课程成绩分析 ===");
        logger.info("学生ID: {}", studentId);
        
        try {
            List<Map<String, Object>> courseScores = scoreAnalysisMapper.getCourseAverageScores(studentId);
            logger.info("查询课程分析数据: {}", courseScores);
            
            List<ScoreAnalysisDTO.CourseScoreAnalysis> result = new ArrayList<>();
            
            for (Map<String, Object> courseData : courseScores) {
                ScoreAnalysisDTO.CourseScoreAnalysis course = new ScoreAnalysisDTO.CourseScoreAnalysis();
                course.setCourseName((String) courseData.get("course_name"));
                course.setAverageScore(DataTypeConverter.toBigDecimal(courseData.get("average_score")));
                course.setExamCount(DataTypeConverter.toInteger(courseData.get("exam_count")));
                
                // 获取该课程的详细成绩
                // 需要根据课程名称获取课程ID，然后查询详细成绩
                String courseName = (String) courseData.get("course_name");
                List<Map<String, Object>> courseDetails = scoreAnalysisMapper.getCourseScoreDetails(studentId, getCourseIdByName(courseName));
                logger.info("课程[{}]的详细成绩: {}", courseName, courseDetails);
                
                List<BigDecimal> scores = new ArrayList<>();
                List<String> examNames = new ArrayList<>();
                List<BigDecimal> totalScores = new ArrayList<>();
                
                for (Map<String, Object> detail : courseDetails) {
                    scores.add(DataTypeConverter.toBigDecimal(detail.get("score")));
                    examNames.add((String) detail.get("exam_name"));
                    if (detail.get("total_score") != null) {
                        totalScores.add(DataTypeConverter.toBigDecimal(detail.get("total_score")));
                    } else {
                        totalScores.add(new BigDecimal(100)); // 默认100分
                    }
                }
                
                course.setScores(scores);
                course.setExamNames(examNames);
                course.setTotalScores(totalScores);
                
                result.add(course);
            }
            
            logger.info("课程分析数据处理完成: {}", result);
            return result;
            
        } catch (Exception e) {
            logger.error("获取课程成绩分析失败", e);
            throw new RuntimeException("获取课程成绩分析失败", e);
        }
    }
    
    /**
     * 根据课程名称获取课程ID
     */
    private Long getCourseIdByName(String courseName) {
        try {
            Long courseId = scoreAnalysisMapper.getCourseIdByName(courseName);
            logger.info("课程[{}]的ID: {}", courseName, courseId);
            return courseId != null ? courseId : 1L; // 如果查询不到，返回默认值
        } catch (Exception e) {
            logger.warn("获取课程ID失败，使用默认值: {}", e.getMessage());
            return 1L; // 默认返回第一个课程ID
        }
    }
    
    @Override
    public ScoreAnalysisDTO.ScoreTrend getScoreTrend(String studentId) {
        logger.info("=== 开始获取成绩趋势数据 ===");
        logger.info("学生ID: {}", studentId);
        
        try {
            List<Map<String, Object>> trendData = scoreAnalysisMapper.getScoreTrend(studentId);
            logger.info("查询趋势数据: {}", trendData);
            
            ScoreAnalysisDTO.ScoreTrend trend = new ScoreAnalysisDTO.ScoreTrend();
            List<String> dates = new ArrayList<>();
            List<BigDecimal> scores = new ArrayList<>();
            List<String> examNames = new ArrayList<>();
            
            for (Map<String, Object> data : trendData) {
                dates.add((String) data.get("exam_date"));
                scores.add(DataTypeConverter.toBigDecimal(data.get("score")));
                examNames.add((String) data.get("exam_name"));
            }
            
            trend.setExamDates(dates);
            trend.setScores(scores);
            trend.setExamNames(examNames);
            
            logger.info("趋势数据构建完成: {}", trend);
            return trend;
            
        } catch (Exception e) {
            logger.error("获取成绩趋势数据失败", e);
            throw new RuntimeException("获取成绩趋势数据失败", e);
        }
    }
    
    @Override
    public ScoreAnalysisDTO.ScoreDistribution getScoreDistribution(String studentId) {
        logger.info("=== 开始获取成绩分布数据 ===");
        logger.info("学生ID: {}", studentId);
        
        try {
            List<Map<String, Object>> distributionData = scoreAnalysisMapper.getScoreDistribution(studentId);
            logger.info("查询分布数据: {}", distributionData);
            
            ScoreAnalysisDTO.ScoreDistribution distribution = new ScoreAnalysisDTO.ScoreDistribution();
            List<String> ranges = new ArrayList<>();
            List<Integer> counts = new ArrayList<>();
            
            for (Map<String, Object> data : distributionData) {
                ranges.add((String) data.get("score_range"));
                counts.add(DataTypeConverter.toInteger(data.get("count")));
            }
            
            distribution.setRanges(ranges);
            distribution.setCounts(counts);
            
            logger.info("分布数据构建完成: {}", distribution);
            return distribution;
            
        } catch (Exception e) {
            logger.error("获取成绩分布数据失败", e);
            throw new RuntimeException("获取成绩分布数据失败", e);
        }
    }
    
    @Override
    public List<Map<String, Object>> getRecentExamRecords(String studentId, Integer limit) {
        logger.info("=== 开始获取最近考试记录 ===");
        logger.info("学生ID: {}, 限制数量: {}", studentId, limit);
        
        try {
            List<Map<String, Object>> records = scoreAnalysisMapper.getRecentExamRecords(studentId, limit);
            logger.info("查询最近考试记录: {}", records);
            
            // 处理数据类型转换
            for (Map<String, Object> record : records) {
                if (record.get("score") != null) {
                    record.put("score", DataTypeConverter.toInteger(record.get("score")));
                }
                if (record.get("total_score") != null) {
                    record.put("total_score", DataTypeConverter.toInteger(record.get("total_score")));
                }
            }
            
            logger.info("最近考试记录处理完成: {}", records);
            return records;
            
        } catch (Exception e) {
            logger.error("获取最近考试记录失败", e);
            throw new RuntimeException("获取最近考试记录失败", e);
        }
    }
    
    @Override
    public Map<String, Object> getExamScoreDetail(String studentId, Long examId) {
        logger.info("=== 开始获取考试详情 ===");
        logger.info("学生ID: {}, 考试ID: {}", studentId, examId);
        
        try {
            // 获取考试基本信息
            List<Map<String, Object>> records = scoreAnalysisMapper.getRecentExamRecords(studentId, 100);
            Map<String, Object> examRecord = records.stream()
                    .filter(record -> record.get("record_id").equals(examId))
                    .findFirst()
                    .orElse(null);
            
            if (examRecord != null) {
                // 获取班级排名
                Long rank = scoreAnalysisMapper.getClassRank(studentId, examId);
                examRecord.put("class_rank", rank);
                
                // 获取班级平均分
                BigDecimal classAverage = scoreAnalysisMapper.getClassAverage(studentId, examId);
                examRecord.put("class_average", classAverage);
                
                // 处理数据类型转换
                if (examRecord.get("score") != null) {
                    examRecord.put("score", DataTypeConverter.toInteger(examRecord.get("score")));
                }
                if (examRecord.get("total_score") != null) {
                    examRecord.put("totalScore", DataTypeConverter.toInteger(examRecord.get("total_score")));
                }
                if (examRecord.get("class_rank") != null) {
                    examRecord.put("classRank", DataTypeConverter.toInteger(examRecord.get("class_rank")));
                }
            }
            
            logger.info("考试详情处理完成: {}", examRecord);
            return examRecord;
            
        } catch (Exception e) {
            logger.error("获取考试详情失败", e);
            throw new RuntimeException("获取考试详情失败", e);
        }
    }
    
    @Override
    public Long getClassRank(String studentId, Long examId) {
        return scoreAnalysisMapper.getClassRank(studentId, examId);
    }
    
    @Override
    public Double getClassAverage(String studentId, Long examId) {
        BigDecimal avg = scoreAnalysisMapper.getClassAverage(studentId, examId);
        return avg != null ? avg.doubleValue() : 0.0;
    }
    
    @Override
    public String askAI(String studentId, String question) {
        // 获取学生成绩数据
        List<Map<String, Object>> exams = scoreAnalysisMapper.getRecentExamRecords(studentId, 10);
        StringBuilder sb = new StringBuilder();
        sb.append("学生最近考试成绩数据如下：\n");
        for (Map<String, Object> exam : exams) {
            sb.append("考试：").append(exam.get("exam_name")).append(", 课程：").append(exam.get("course_name"))
              .append(", 得分：").append(exam.get("score")).append("/ ").append(exam.get("total_score"))
              .append(", 时间：").append(exam.get("submit_time")).append("\n");
        }
        String prompt = sb.toString() + "\n" + question;
        return DeepSeekUtil.askDeepSeek(prompt);
    }

    @Override
    public String askAISuggestion(String studentId) {
        List<Map<String, Object>> exams = scoreAnalysisMapper.getRecentExamRecords(studentId, 10);
        StringBuilder sb = new StringBuilder();
        sb.append("你是一名善于分析学生成绩并给出学习建议的学习顾问。以下是学生最近的考试成绩数据：\n");
        for (Map<String, Object> exam : exams) {
            sb.append("考试：").append(exam.get("exam_name")).append(", 课程：").append(exam.get("course_name"))
              .append(", 得分：").append(exam.get("score")).append("/ ").append(exam.get("total_score"))
              .append(", 时间：").append(exam.get("submit_time")).append("\n");
        }
        sb.append("请分析学生的成绩，指出薄弱环节，并给出具体的学习建议和方法优化建议。");
        return DeepSeekUtil.askDeepSeek(sb.toString());
    }
} 